<template>
  <!-- 音乐播放器封装 -->
  <div class="player">
    <div class="player-container">
      <!-- 歌单信息 -->
      <div class="player-left">
        <img :src="imgInfo.imgUrl" alt="" @click="openPlayView" />
        <div class="music-info">
          <div class="font-14 w-150 text-hidden">{{ imgInfo.name }}</div>
          <div class="font-14 w-100 text-hidden">{{ imgInfo.author }}</div>
        </div>
      </div>
      <!-- 播放器 -->
      <div class="player-wrapper">
        <!-- 按钮 -->
        <div class="player-bar">
          <!-- 列表 -->
          <button class="player-bar-btn">
            <i class="iconfont icon-liebiaoshunxu"></i>
          </button>
          <!-- 上一首 -->
          <button
            class="player-bar-btn"
            @click="lastMusic"
            :class="{ 'player-bar-btn_disabled': playType === 'personalFm' }"
          >
            <i class="iconfont icon-shangyishou"></i>
          </button>
          <!-- 暂停 -->
          <button class="player-bar-btn" @click="pause">
            <i v-show="isPlay" class="iconfont icon-zanting"></i>
            <i v-show="!isPlay" class="iconfont icon-bofang"></i>
          </button>
          <!-- 下一首 -->
          <button class="player-bar-btn" @click="nextMusic">
            <i class="iconfont icon-xiayishou"></i>
          </button>
          <!-- 爱心 -->
          <button class="player-bar-btn" @click="likeMusic">
            <i v-show="!isLiked" class="iconfont icon-aixin1"></i>
            <i
              v-show="isLiked"
              style="color: brown"
              class="iconfont icon-aixin1"
            ></i>
          </button>
        </div>
        <!-- 进度条 -->
        <div class="time-progress">
          <span class="font-12">{{
            currenMusicInfo.currenTime | timeFormat
          }}</span>
          <el-slider
            v-model="curren"
            class="timeSlider"
            :show-tooltip="false"
            :disabled="musicUrl === ''"
            @change="changeCurrenTime"
          >
          </el-slider>
          <span class="font-12">{{
            (currenMusicInfo.totalTime / 1000) | timeFormat
          }}</span>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="btn-other">
        <!-- 下载 -->
        <div class="dowmload">
          <i
            class="el-icon-download volume-icon mright-20 pointer"
            @click="download"
          ></i>
        </div>
        <!-- 音量 -->
        <div class="volume">
          <div @click="isMute = !isMute">
            <i
              v-if="volume == 0"
              class="iconfont icon-shengyinguanbi volume-icon pointer"
            ></i>
            <i v-else class="iconfont icon-shengyin volume-icon pointer"></i>
          </div>
          <div class="volume-slider">
            <el-slider v-model="volume" vertical height="200px"> </el-slider>
          </div>
        </div>
        <!-- 当前播放列表 -->
        <div class="current-list" v-show="playType !== 'personalFm'">
          <i
            class="iconfont icon-liebiaoshunxu volume-icon pointer"
            @click="showList"
          ></i>
        </div>
      </div>
    </div>
    <audio
      ref="audioRef"
      :src="musicUrl"
      autoplay
      @ended="nextMusic"
      @timeupdate="updateCurrenTime"
    ></audio>
    <!-- 侧边抽屉 -->
    <el-drawer
      title="当前播放"
      :visible.sync="musicListDrawerTableVisible"
      direction="rtl"
      size="30%"
    >
      <div class="drawerTitle">
        <span v-if="musicUrl">总共{{ musicList.length }}首歌曲</span>
        <span v-if="musicUrl">现在播放第{{ currenIndex + 1 }}首</span>
        <span v-else>当前无音乐播放</span>
      </div>
      <div class="border"></div>
      <el-table :data="musicList" @row-dblclick="playMusic">
        <el-table-column type="index" label="#" width="50">
          <template v-slot="scope">
            <span style="color: red" v-if="showCurren(scope.row.id)">
              <i v-if="isPlay" class="iconfont icon-shengyin_shiti"></i>
              <i v-else class="iconfont icon-sound"></i>
            </span>
            <span v-else style="color: #c3c3db">{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="name"
          label="歌名"
          width="200"
        ></el-table-column>
        <el-table-column
          property="ar[0].name"
          label="歌手"
          width="100"
        ></el-table-column>
        <el-table-column property="dt" label="时间" width="100">
          <template v-slot="scope">
            <span>{{ (scope.row.dt / 1000) | timeFormat }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <!-- 播放界面 -->
    <el-drawer
      :visible.sync="playViewDrawer"
      direction="btt"
      :before-close="handleClose"
      :show-close="false"
      :modal="false"
      size="100%"
    >
      <template #title>
        <div>
          <i class="el-icon-arrow-down pointer" @click="handleClose"></i>
        </div>
      </template>
      <div class="play-view">
        <div class="music-info">
          <div class="music-title">{{ imgInfo.name }}</div>
          <div class="music-author">{{ imgInfo.author }}</div>
          <div class="lyric-view">
            <div class="img-wrap">
              <div
                class="changzhen pointer"
                :class="{ 'changchen-active': isPlay }"
                @click="pause"
              >
                <img src="@/assets/img/changzhen.png" alt="" />
              </div>
              <div class="changpian" :class="{ 'changpian-active': isPlay }">
                <div class="changpian-wrap">
                  <img :src="imgInfo.imgUrl" alt="" />
                </div>
              </div>
            </div>
            <LyricWrap
              :musicId="currenMusicId"
              :currenTime="currenMusicInfo.currenTime"
            ></LyricWrap>
          </div>
        </div>
        <div class="comment-view mtop-50">
          <Comment
            :hotCommentList="hotCommentList"
            :newCommentList="newCommentList"
            :type="0"
            :id="currenMusicId"
            @getNew="getNewCommentList"
          ></Comment>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="newParams.pageNo"
            :page-size="newParams.pageSize"
            layout="prev, pager, next"
            :total="total"
            align="center"
            background
          >
          </el-pagination>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
let imgUrl = require("@/assets/img/music.jpg");
import {
  getMusicUrl,
  likeMusic,
  getHotComment,
  getComment,
} from "@/api/request";
import { mapState } from "vuex";
import LyricWrap from "@/components/player/LyricWrap.vue";
import Comment from "@/components/list/commentList.vue";
export default {
  components: { LyricWrap, Comment },
  data() {
    return {
      curren: 0,
      imgInfo: {
        imgUrl: imgUrl,
        name: "未知歌名",
        author: "未知歌手名",
      },
      musicUrl: "",
      volume: 50, //音量
      isMute: false, //是否静音
      saveVolume: 50, //保存当前的音量
      //是否打开侧边栏
      musicListDrawerTableVisible: false,
      //是否打开音乐播放界面
      playViewDrawer: false,
      hotCommentList: [],
      newCommentList: [],
      newParams: {
        id: 0,
        type: 0,
        pageNo: 1,
        pageSize: 10,
        sortType: 3,
        cursor: 0,
      },
      total: 0,
    };
  },
  computed: {
    ...mapState([
      "isLogin",
      "musicList",
      "currenMusicId",
      "currenIndex",
      "playType",
      "isPlay",
      "likeIdList",
      "currenMusicInfo",
    ]),
    isLiked: {
      get() {
        return this.likeIdList.indexOf(this.currenMusicId) !== -1;
      },
      set(val) {
        if (this.isLiked) {
          this.$store.commit("setLikeIdList", {
            type: "remove",
            data: val,
          });
        } else {
          this.$store.commit("setLikeIdList", {
            type: "unshift",
            data: val,
          });
        }
      },
    },
  },
  watch: {
    currenMusicId() {
      console.log("音乐发生变化");
      this.newParams.id = this.currenMusicId;
      this.getMusicUrl();
      this.getHotCommentList();
      this.getNewCommentList();
      this.setHistory();
    },
    //通过vuex管理的播放状态，audio会判断是否播放
    isPlay(val) {
      // 在musicUrl改变之后获取
      if (this.musicUrl === "") return;
      if (val) {
        this.$refs.audioRef.play();
      } else {
        this.$refs.audioRef.pause();
      }
    },
    //监听静音状态
    isMute(val) {
      if (val) {
        this.saveVolume = this.volume;
        this.volume = 0;
      } else {
        this.volume = this.saveVolume = 50;
      }
    },
    //监听音量的变化
    volume(val) {
      this.changeVolume();
    },
  },
  created() {
    this.getHistoryList();
  },
  methods: {
    // 获取历史播放
    getHistoryList(){
      if(!window.localStorage.getItem("historylist")) return;
      this.$store.commit('setHistoryList',{
        type:'get',
        data:JSON.parse(window.localStorage.getItem('historylist'))
      })
    },
    //更新历史播放
    setHistory(){
      this.$store.commit("setHistoryList",{
        type:'unshift',
        data:this.musicList[this.currenIndex]
      })
    },
    //获取歌曲基本信息
    getImgInfo() {
      console.log(this.musicList);
      if (this.musicList[this.currenIndex].al.picUrl) {
        this.imgInfo.imgUrl = this.musicList[this.currenIndex].al.picUrl;
      } else {
        this.imgInfo.imgUrl = imgUrl;
      }
      this.imgInfo.author = this.musicList[this.currenIndex].ar[0].name;
      this.imgInfo.name = this.musicList[this.currenIndex].name;
    },
    //获取歌曲时长
    getTolTiem() {
      this.$store.commit("setTotalTime", this.musicList[this.currenIndex].dt);
    },
    //音乐播放连接
    async getMusicUrl() {
      this.getTolTiem();
      this.getImgInfo();
      const { data: res } = await getMusicUrl(this.currenMusicId);
      if (res.code !== 200) return this.$message.error("播放失败");
      if (!res.data[0].url) {
        const h = this.$createElement;
        this.$notify({
          title: "当前歌曲暂无音源",
          message: h(
            "i",
            { style: "color: teal" },
            "因版权方要求，该资源暂时无法播放，我们正在争取歌曲回归"
          ),
        });
        this.musicUrl = "";
        this.$store.commit("setPlayState", false);
        return;
      }
      this.musicUrl = res.data[0].url;
    },
    //上一首
    lastMusic() {
      if (this.playType == "music") {
        if (this.currenIndex != 0) {
          this.$store.commit("setCurrenIndex", this.currenIndex - 1);
          this.$store.commit(
            "setCurrenMusicId",
            this.musicList[this.currenIndex].id
          );
        } else {
          this.$store.commit("setPlayState", false);
          this.$message.error("没有上一首");
        }
      } else if (this.playType == "personalFm") {
        return false;
      }
    },
    // 下一首
    nextMusic() {
      if (this.playType == "music") {
        if (this.currenIndex !== this.musicList.length - 1) {
          this.$store.commit("setCurrenIndex", this.currenIndex + 1);
          this.$store.commit(
            "setCurrenMusicId",
            this.musicList[this.currenIndex].id
          );
        } else {
          this.$store.commit("setPlayState", false);
          this.$message.error("已经是最后一首了");
        }
      } else if(this.playType === 'personalFm'){
        this.$store.dispatch('getPersonalFm',{type : 'next'})
      }
    },
    // 暂停
    pause() {
      console.log("暂停");
      this.$store.commit("setPlayState", !this.isPlay);
    },
    // 喜欢
    async likeMusic() {
      if (!this.isLogin) return this.$message.error("请先登录");
      if (
        this.currenMusicId === 0 ||
        typeof this.currenMusicId == "undefined"
      ) {
        return;
      }
      const { data: res } = await likeMusic(this.currenMusicId, !this.isLiked);
      if (res.code !== 200) return;
      this.$message.success(`${this.isliked ? "取消喜欢" : "喜欢"} 成功`);
      this.isLiked = this.currenMusicId;
    },
    //更新当前播放时间
    updateCurrenTime() {
      if (!this.$refs.audioRef) return;
      // 通过audio对象的方法后去当前时间
      let time = this.$refs.audioRef.currentTime;
      time = Math.floor(time);
      // 同步进度条
      if (time != this.currenMusicInfo.currenTime) {
        this.$store.commit("setCurrenTime", time);
        let percent =
          ((this.currenMusicInfo.currenTime * 1000) /
            this.currenMusicInfo.totalTime) *
          100;
        percent = Math.floor(percent);
        this.curren = percent;
      }
    },
    //拖动进度条
    changeCurrenTime(val) {
      let time = ((val / 100) * this.currenMusicInfo.totalTime) / 1000;
      this.$refs.audioRef.currentTime = time;
    },
    //拖动进度条改变音量
    changeVolume() {
      this.$refs.audioRef.volume = this.volume / 100;
    },
    download() {
      if (this.musicUrl == "") return;
      this.$message.error("没有下载权限");
    },
    showList() {
      this.musicListDrawerTableVisible = !this.musicListDrawerTableVisible;
    },
    //播放侧边抽屉的音乐
    playMusic(row) {
      this.$store.dispatch("playMusic", {
        list: this.musicList,
        id: row.id,
      });
    },
    //打开音乐播放界面
    openPlayView() {
      if (this.musicUrl) {
        this.playViewDrawer = true;
      }
    },
    //关闭音乐播放界面
    handleClose() {
      this.playViewDrawer = false;
    },
    //获取热门评论
    async getHotCommentList() {
      const { data: res } = await getHotComment(this.currenMusicId, 0, 10);
      if (res.code !== 200) return;
      this.hotCommentList = res.hotComments;
    },
    //获取最新评论
    async getNewCommentList() {
      const { data: res } = await getComment(this.newParams);
      if (res.code !== 200) return;
      this.newCommentList = res.data.comments;
      this.newParams.cursor = res.data.cursor;
      this.total = res.data.totalCount;
    },
    //分页器回调
    handleCurrentChange(val) {
      this.newParams.pageNo = val;
      this.newParams.sortType = 3;
      this.$scrollTo();
      this.getNewCommentList();
    },
    showCurren(id) {
      return this.currenMusicId === id;
    },
  },
};
</script>

<style lang="less" scoped>
.player {
  height: 100%;
}
.player-container {
  box-sizing: border-box;
  border-top: 1px solid #eeeeee;
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
}
// 播放器左边的信息区域
.player-left {
  display: flex;
  align-items: center;
  position: relative;
  width: 300px;
  img {
    margin: 0 10px;
    height: 50px;
    width: 50px;
    border-radius: 5%;
    cursor: pointer;
  }
  &-info {
    margin: 10px;
    line-height: 20px;
  }
}
// 中间按钮
.player-bar {
  width: 300px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  margin-top: 6px;
  justify-content: space-around;
  &-btn {
    outline: none;
    border: none;
    background-color: #fff;
    cursor: pointer;
    .iconfont {
      font-size: 18px;
    }
    &:nth-child(3) {
      height: 32px;
      width: 32px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      .iconfont {
        font-size: 16px;
      }
    }
    &:hover {
      color: red;
    }
  }
}
.player-bar-btn_disabled{
  cursor: not-allowed;
  color: #e5e5e5;
}
.time-progress {
  line-height: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.timeSlider {
  width: 460px;
  margin: 0 10px;
}
// 右侧按钮
.btn-other {
  display: flex;
  width: 300px;
  justify-content: flex-end;
}
.volume-icon {
  font-size: 30px;
}
.volume {
  position: relative;
  margin-right: 20px;
  .volume-slider {
    display: none;
    position: absolute;
    top: -220px;
    left: -3px;
    background-color: #fff;
    padding: 10px 0;
    border-radius: 5px;
    box-shadow: 0 0 10px #bbbbbb;
  }
  &:hover .volume-slider {
    display: block;
  }
}
.drawerTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 100px;
}
.border {
  border: 1px solid #bbbbbb;
  background-color: #bbbbbb;
}
.play-view {
  width: 100%;
  margin: 0 auto;
  padding: 0 20%;
  .music-info {
    margin: 0 auto;
    .music-title {
      text-align: center;
      font-size: 30px;
    }
    .music-author {
      margin-top: 10px;
      text-align: center;
    }
  }
  .comment-view {
    margin-bottom: 80px;
  }
}

// 歌词以及唱片
.lyric-view {
  margin: 0px 150px;
  display: flex;
  .img-wrap {
    position: relative;
    .changzhen {
      position: absolute;
      top: -20px;
      left: 100px;
      width: 120px;
      transform-origin: 3px 3px;
      transition: all 0.5s;
      z-index: 20;
      img {
        width: 120px;
      }
    }
    .changpian {
      margin-top: 40px;
      width: 260px;
      height: 260px;
      border-radius: 50%;
      background-color: #c4c3c5;
      display: flex;
      justify-content: center;
      align-items: center;
      .changpian-wrap {
        width: 240px;
        height: 240px;
        background-color: #1a1c1e;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 180px;
          height: 180px;
          border-radius: 50%;
        }
      }
    }
  }
}
.changchen-active {
  transform: rotate(30deg);
}
.changpian-active {
  animation: circle 30s infinite linear;
}
@keyframes circle {
  from {
    transform: rotate(0);
  }

  to {
    transform: rotate(360deg);
  }
}
/deep/.el-drawer__header {
  margin-bottom: 0px;
}
</style>